package com.hsogoo.study.springmvc.initializer;

import com.hsogoo.study.springmvc.service.Hello;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @Author huangsaigang
 * Created @2019-09-26.
 */
@HandlesTypes(Hello.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> helloClasses, ServletContext servletContext) throws ServletException {

        if(!CollectionUtils.isEmpty(helloClasses)){
            List<Hello> initializers = new LinkedList<>();
            for (Class<?> waiClass : helloClasses) {
                // Be defensive: Some servlet containers provide us with invalid classes,
                // no matter what @HandlesTypes says...
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        Hello.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((Hello)
                                ReflectionUtils.accessibleConstructor(waiClass).newInstance());
                    }
                    catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                    }
                }
            }
            for(Hello initializer : initializers){
                initializer.sayHello();
            }
        }

    }
}
